/*
 * @Author: hejian@myhexin.com
 * @Date: 2018-12-18 14:50:52
 * @Last Modified by: hejian@myhexin.com
 * @Last Modified time: 2019-02-15 10:09:31
 * @desc 构造函数和原型组合模式实现日历控件
 */

(function ($, window, document, undefined) {
  // 构造函数
  var nowDate;
  var selDate
  var Calendar = function (elem, options) {
    // 祖先dom
    this.$calendar = elem;
    nowDate = options.date;
    selDate = nowDate;
    this.weeknum = thisweek(nowDate)[1];
    // 第几个日历
    this.number = options.number;
    // 是否显示涨停详情
    this.showGotoDetail = options.showGotoDetail;
    // 点击完整的月day
    this.clickListDay = options.clickListDay;
    // 点击折叠的day
    this.clickWeekDay = options.clickWeekDay;
    // 去涨停详情
    this.clickDetail = options.clickDetail;
    // 点击折叠
    this.clickFold = options.clickFold;
    // 返回当天
    this.backToday = options.backToday;
    // 右划
    this.moveRight = options.moveRight;
    // 左滑
    this.moveLeft = options.moveLeft;
  };
  // 原型链
  Calendar.prototype = {
    // 填充一月日子dom
    showCalendar: function (from) {
      var that = this;
      if (typeof nowDate == 'string') {
        var _year = nowDate.split("-")[0] - 0;
        var _month = nowDate.split("-")[1] - 1;
        var _day = nowDate.split("-")[2] - 0;
      }
      // 计算当前的年份
      if (that.number == 1) {
        var year = dateObj.getDate().getFullYear();
        var month = dateObj.getDate().getMonth();
        var day = dateObj.getDate().getDate();
        var dateStr = returnDateStr(dateObj.getDate());
      } else if (that.number == 2) {
        var year = dateObj2.getDate().getFullYear();
        var month = dateObj2.getDate().getMonth();
        var day = dateObj.getDate().getDate();
        var dateStr = returnDateStr(dateObj2.getDate());
      }
      // 获取当月的第一天
      var firstDay = new Date(year, month, 1);
      this.$calendarDate_item.each(function (i) {
        // 得到当前列表显示的所有日子 6*7结构
        var allDay = new Date(year, month, i + 1 - firstDay.getDay());
        // 把日子转换成yyyy-mm-dd形式
        var allDay_str = returnDateStr(allDay);
        // 写上日子，再附上yymmdd的时间
        $(this).text(allDay.getDate()).data("date", allDay_str).data("index", i);
        // 如果是当前日子，那么就高亮一下
        if (returnDateStr(new Date(_year, _month, _day)) === allDay_str) {
          $(this).attr("class", "item item-curMonth item-curSelDay").data("day", "0");
          if (
            changingStr(allDay_str).getDay() === 0 ||
            changingStr(allDay_str).getDay() === 6
          ) {
            $(this).removeClass("item-curMonth");
          }
          that.curSelDay2 = i;
          that.curDay = dateStr;
          // 如果是这个月日子，就加黑一下
        } else if (
          returnDateStr(firstDay).substr(0, 7) === allDay_str.substr(0, 7) &&
          changingStr(allDay_str).getDay() !== 0 &&
          changingStr(allDay_str).getDay() !== 6
        ) {
          $(this).attr("class", "item item-curMonth").data("day", "1");
          // 如果是上个月日子，就置灰一下
        } else {
          $(this).attr("class", "item").data("day", "-1");
        }
        if (from == "switch") {
          if (that.selDate != "") {
            $(this).removeClass("item-curSelDay");
          }
          if ($(this).data("date") == that.selDate) {
            $(this).addClass("item-curSelDay");
          }
        }
      });
      if (from == 'switch' || from == 'back') {
        month = month >= 9 ? month + 1 : "0" + (month + 1)
        that.$titleStr.text(year + "-" + month)
      }
    },
    // 填充一周日子dom
    showCalendarWeek: function (year, weeknum, from) {
      var that = this;
      var newdate = "";
      if (that.number == 1) {
        var year = dateObj.getDate().getFullYear();
        var month = dateObj.getDate().getMonth();
      } else if (that.number == 2) {
        var year = dateObj.getDate().getFullYear();
        var month = dateObj2.getDate().getMonth();
      }
      //获取周第一天日期
      var datastart = weekFirstDay(year, weeknum);
      // 获取当月的第一天
      var firstDay = new Date(year, month, 1);
      // 获取今天时间数组
      var todayarr = todaydate(that.selDate);
      // 拼接时间
      var dateStr = todayarr.join("-");
      this.$calendarDate_item_week.each(function (i) {
        newdate = new Date(datastart[0], datastart[1], datastart[2] + i);
        $(this).text(newdate.getDate()).data("date", returnDateStr(newdate)).data("index", i);
        if (from == "back") {
          if (that.selDate != "") {
            $(this).removeClass("item-curSelDay");
          }
          if (($(this).data("day") - 0) == 0) {
            $(this).addClass('item-curSelDay')
          }
          that.$titleStr.text(year + "-" + (month + 1))
        } else {
          if (
            newdate.getFullYear() == todayarr[0] &&
            newdate.getMonth() == todayarr[1] &&
            newdate.getDate() == todayarr[2] &&
            !that.date
          ) {
            $(this).attr("class", "item item-curMonth item-curSelDay").data("day", "0");
            // 如果不是这周的日子
            if (
              changingStr(returnDateStr(newdate)).getDay() === 0 ||
              changingStr(returnDateStr(newdate)).getDay() === 6
            ) {
              $(this).removeClass("item-curMonth");
            }
            that.curSelDay = i;
            that.curDay = dateStr;
            // 是这周的时间
          } else if (
            firstDay.getMonth() === newdate.getMonth() &&
            changingStr(returnDateStr(newdate)).getDay() !== 0 &&
            changingStr(returnDateStr(newdate)).getDay() !== 6
          ) {
            $(this).attr("class", "item item-curMonth").data("day", "1");
            // 如果是上周的日子
          } else {
            $(this).attr("class", "item").data("day", "-1");
          }
          if (returnDateStr(newdate) === that.date) {
            $(this).attr("class", "item item-curMonth item-curSelDay").data("day", "1");
          }
        }
      });
      var _weekLastDay = $(
        that.$calendarDate_item_week[that.$calendarDate_item_week.length - 1]
      ).data("date");
      var _listLastDay = $(
        that.$calendarDate_item[that.$calendarDate_item.length - 1]
      ).data("date");
      var _weekFirstDay = $(that.$calendarDate_item_week[0]).data("date");
      var _listFirstDay = $(that.$calendarDate_item[0]).data("date");
      if (_weekLastDay === _listLastDay) {
        this.$next.css("visibility", "hidden");
      } else {
        this.$next.css("visibility", "visible");
      }
      if (_weekFirstDay === _listFirstDay) {
        this.$prev.css("visibility", "hidden");
      } else {
        this.$prev.css("visibility", "visible");
      }
      if (from == 'back') {
        month = month > 9 ? month + 1 : "0" + (month + 1)
        that.$titleStr.text(year + "-" + month)
      }
    },
    // 渲染DOM
    renderDOM: function () {
      // 标题dom结构
      this.$calendar_title = $('<div class="calendar-title clearfix"></div>');
      // 周dom结构
      this.$calendar_week = $('<ul class="calendar-week"></ul>');
      // 日子dom结构
      this.$calendar_date = $(
        '<ul class="calendar-date" style="display:none"></ul>'
      );
      // 周dom结构
      this.$calendar_date_week = $('<ul class="calendar-date-week"></ul>');
      // 展开收起按钮
      this.$fold_btn = $('<span class="fold"></span>');
      // 上一周
      this.$prev = $('<p class="prev" style="display:none">上一周</p>');
      // 下一周
      this.$next = $('<p class="next" style="display:none">下一周</p>');
      // 折叠区域
      this.$foldarea = $('<div class="foldarea"></div>');
      // 提示
      this.$tips = $('<p class="tips">提示：只展示共35日内的交易日数据</p>');
      // 标题
      this.$titleStr = $('<a href="javascript:;" class="date"></a>');
      // 涨停详情
      this.$limitDetail = $('<span class="limit-detail">涨停详情</span>');
      // 回到最新
      this.$backToday = $(
        '<span class="backtoday" style="display:none">回到最新</span>'
      );
      // 周
      var _weekStr =
        '<li class="item r">日</li>' +
        '<li class="item">一</li>' +
        '<li class="item">二</li>' +
        '<li class="item">三</li>' +
        '<li class="item">四</li>' +
        '<li class="item">五</li>' +
        '<li class="item l">六</li>';
      // 日子
      var _dateStr = "";
      var _weekDay = "";
      // 遍历
      for (var i = 0; i < 6; i++) {
        _dateStr +=
          '<li class="item">--</li>' +
          '<li class="item">--</li>' +
          '<li class="item">--</li>' +
          '<li class="item">--</li>' +
          '<li class="item">--</li>' +
          '<li class="item">--</li>' +
          '<li class="item">--</li>';
      }
      for (var j = 0; j < 7; j++) {
        _weekDay += '<li class="item">--</li>';
      }
      // 日历的标题dom
      if (this.showGotoDetail) {
        this.$calendar_title.append(
          this.$titleStr,
          this.$limitDetail,
          this.$backToday
        );
      } else {
        this.$calendar_title.append(this.$titleStr, this.$backToday);
      }
      // 日历的周dom
      this.$calendar_week.html(_weekStr);
      // 日历的日子dom
      this.$calendar_date.html(_dateStr);
      // 一周日子dom
      this.$calendar_date_week.html(_weekDay);
      // 折叠区域
      this.$foldarea.append(this.$prev, this.$fold_btn, this.$next);
      // 把这些插入父级dom里
      this.$calendar.append(
        this.$calendar_title,
        this.$calendar_week,
        this.$calendar_date_week,
        this.$foldarea,
        this.$calendar_date,
        this.$calendar_today,
        this.$tips
      );
      // 插入完显示
      this.$calendar.show();
    },
    // 初始化操作
    inital: function () {
      // this指向当前的构造函数
      var that = this;
      var flag = false;
      var number = 1;
      var touch = {};
      if (that.number == 1) {
        var arr = [parseInt(nowDate.split("-")[0]), parseInt(nowDate.split("-")[1]) - 1, parseInt(nowDate.split("-")[2])];
        dateObj.setDate(new Date(arr[0], arr[1], arr[2]))
      } else if (that.number == 2) {
        var arr = [parseInt(nowDate.split("-")[0]), parseInt(nowDate.split("-")[1]) - 1, parseInt(nowDate.split("-")[2])];
        dateObj2.setDate(new Date(arr[0], arr[1], arr[2]))
      }
      that.selDate = nowDate;
      // 先渲染dom
      this.renderDOM();
      // 获取左上角显示的日期dom
      this.$calendarTitle_text = this.$calendar_title.find(".date");
      // 获取日子的dom
      this.$calendarDate_item = this.$calendar_date.find(".item");
      //  获取周日子的dom
      this.$calendarDate_item_week = this.$calendar_date_week.find(".item");
      // 填充日子dom
      this.showCalendar();
      // 设置标题时间
      this.$calendarTitle_text.text(nowDate.slice(0, 7));
      // 填充周日子dom
      this.showCalendarWeek(thisweek(nowDate)[0], thisweek(nowDate)[1]);
      // 切换月份
      this.$calendar_date.on("touchstart", function (e) {
        touch.startX = e.changedTouches[0].pageX;
        touch.startY = e.changedTouches[0].pageY;
        $(this).on("touchmove", function (e) {
          e.preventDefault();
          touch.pageX = e.changedTouches[0].pageX;
          touch.pageY = e.changedTouches[0].pageY;
          if (
            touch.pageX - touch.startX > 20 &&
            touch.pageY - touch.startY < 5
          ) {
            if (number <= 2) {
              number++;
              if (that.number == 1) {
                var _date = dateObj.getDate();
                dateObj.setDate(
                  new Date(_date.getFullYear(), _date.getMonth() - 1, 1)
                );
              } else if (that.number == 2) {
                var _date = dateObj2.getDate();
                dateObj2.setDate(
                  new Date(_date.getFullYear(), _date.getMonth() - 1, 1)
                );
              }
              that.showCalendar("switch");
            } else {
              number = 3;
            }
            that.moveRight();
            $(this).off("touchmove");
          } else if (
            touch.pageX - touch.startX < -10 &&
            touch.pageY - touch.startY < 5
          ) {
            if (number > 1) {
              number--;
              if (that.number == 1) {
                var _date = dateObj.getDate();
                dateObj.setDate(
                  new Date(_date.getFullYear(), _date.getMonth() + 1, 1)
                );
              } else if (that.number == 2) {
                var _date = dateObj2.getDate();
                dateObj2.setDate(
                  new Date(_date.getFullYear(), _date.getMonth() + 1, 1)
                );
              }
              that.showCalendar("switch");
            }
            that.moveLeft();
            $(this).off("touchmove");
          }
        });
      });
      // 回到最新
      this.$backToday.click(function () {
        if (that.number == 1) {
          var arr = [parseInt(nowDate.split("-")[0]), parseInt(nowDate.split("-")[1]) - 1, parseInt(nowDate.split("-")[2])];
          dateObj.setDate(new Date(arr[0], arr[1], arr[2]))
        } else if (that.number == 2) {
          var arr = [parseInt(nowDate.split("-")[0]), parseInt(nowDate.split("-")[1]) - 1, parseInt(nowDate.split("-")[2])];
          dateObj2.setDate(new Date(arr[0], arr[1], arr[2]))
        }
        that.showCalendarWeek(thisweek(nowDate)[0], thisweek(nowDate)[1], 'back');
        that.showCalendar('back');
        that.selDate = nowDate;
        number = 1;
        $(that.$backToday).hide();
        $(that.$limitDetail).show();
        that.backToday();
      });
      //  日子在click的时候
      this.$calendarDate_item.click(function () {
        that.selDate = $(this).data("date");
        if (changingStr($(this).data("date")).getDay() == 0 || changingStr($(this).data("date")).getDay() == 6) {
          return
        }
        if ($(this).data("day") - 0 != 0) {
          $(that.$backToday).show();
          $(that.$limitDetail).hide();
        } else {
          $(that.$backToday).hide();
          $(that.$limitDetail).show();
        }
        // 从周点击返回只触发一次
        if (flag) {
          that.$calendarDate_item.each(function (i) {
            if ($(this).hasClass("item-curSelDay")) {
              $(this).removeClass("item-curSelDay");
            }
          });
          flag = false;
        }
        // 记录索引
        var index = $(this).data("index");
        // 记录点击的日期
        var date = $(this).data("date");
        // 移除上一次点击的日子样式
        $(that.$calendarDate_item[that.curSelDay2]).removeClass(
          "item-curSelDay"
        );
        // 存储这次点击的索引
        that.curSelDay2 = index;
        // 增加选中的样式
        if (that.selDate != "") {
          that.$calendarDate_item.each(function (i) {
            if ($(this).hasClass("item-curSelDay")) {
              $(this).removeClass("item-curSelDay");
            }
          });
        }
        $(this).addClass("item-curSelDay");
        // 更改标题样式
        $(that.$calendarTitle_text).text(date.slice(0, 7));
        that.clickListDay($(this));
      });
      // 周日子在点击的时候
      this.$calendarDate_item_week.click(function () {
        that.selDate = $(this).data("date");
        if (changingStr($(this).data("date")).getDay() == 0 || changingStr($(this).data("date")).getDay() == 6) {
          return
        }
        if ($(this).data("day") - 0 != 0) {
          $(that.$backToday).show();
          $(that.$limitDetail).hide();
        } else {
          $(that.$backToday).hide();
          $(that.$limitDetail).show();
        }
        flag = true;
        // 记录点击的日期
        that.date = $(this).data("date");
        // 移除上一次点击的日子样式
        $(that.$calendarDate_item_week[that.curSelDay]).removeClass(
          "item-curSelDay"
        );
        // 记录索引
        that.$calendarDate_item_week.each(function (i) {
          if ($(this).hasClass("item-curSelDay")) {
            $(this).removeClass("item-curSelDay");
          }
          if ($(this).data("date") == that.date) {
            $(this).addClass("item-curSelDay");
          }
        });
        // 同步完整的日子
        that.$calendarDate_item.each(function (i) {
          if ($(this).hasClass("item-curSelDay")) {
            $(this).removeClass("item-curSelDay");
          }
          if ($(this).data("date") == that.date) {
            $(this).addClass("item-curSelDay");
          }
        });
        // 更改标题样式
        $(that.$calendarTitle_text).text(that.date.slice(0, 7));
        that.clickWeekDay($(this));
      });
      // 展开按钮
      this.$fold_btn.click(function () {
        that.$calendar_date_week.css("display", "none");
        that.$calendar_date.css("display", "block");
        $(this).css("display", "none");
        that.$tips.css("display", "block");
        that.clickFold();
      });
      // 点击详情按钮
      this.$limitDetail.click(function () {
        that.clickDetail();
      });
      this.$next.click(function () {
        that.weeknum += 1;
        var nowweek = thisweek();
        var beforeweekfirst = weekFirstDay(nowweek[0], that.weeknum);
        var beforeweekdata = getweeknum(
          beforeweekfirst[0],
          beforeweekfirst[1],
          beforeweekfirst[2]
        );
        // that.showCalendarWeek(beforeweekdata[0], beforeweekdata[1]);
      });
      this.$prev.click(function () {
        that.weeknum -= 1;
        var nowweek = thisweek();
        var beforeweekfirst = weekFirstDay(nowweek[0], that.weeknum);
        var beforeweekdata = getweeknum(
          beforeweekfirst[0],
          beforeweekfirst[1],
          beforeweekfirst[2]
        );
        // that.showCalendarWeek(beforeweekdata[0], beforeweekdata[1]);
      });
    },
    constructor: Calendar
  };
  // 实例化
  $.fn.calendar = function (options) {
    return new Calendar(this, options).inital();
  };
  // 存储标准化时间
  var dateObj = (function (a) {
    var _date = new Date();
    return {
      getDate: function () {
        return _date;
      },
      setDate: function (date) {
        _date = date;
      }
    };
  })();
  var dateObj2 = (function () {
    var _date = new Date();
    return {
      getDate: function () {
        return _date;
      },
      setDate: function (date) {
        _date = date;
      }
    };
  })(nowDate);

  // 日期转字符串
  function returnDateStr(date) {
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    month = month <= 9 ? "0" + month : "" + month;
    day = day <= 9 ? "0" + day : "" + day;
    return year + "-" + month + "-" + day;
  }
  // 字符串转日期
  function changingStr(fDate) {
    var fullDate = fDate.split("-");
    return new Date(fullDate[0], fullDate[1] - 1, fullDate[2]);
  }
  // 判断是否是闰年
  function is_leap(year) {
    return year % 100 == 0 ?
      (res = year % 400 == 0 ? 1 : 0) :
      (res = year % 4 == 0 ? 1 : 0);
  }
  // 获取每周的第一天
  function weekFirstDay(year, weeknum) {
    //获取当年月份天数数组
    var monthDays = [
      31,
      28 + is_leap(year),
      31,
      30,
      31,
      30,
      31,
      31,
      30,
      31,
      30,
      31
    ];
    //获取当年第一天是周几
    var newYearWeek = new Date(year, 0, 1).getDay();
    //新年到周第一天的总天数
    var weekDays;
    if (newYearWeek < 5) {
      //新年第一天算年内第一周[周四在本年]
      weekDays = 7 * (weeknum - 2) + (7 - newYearWeek + 1);
    } else {
      //新年第一天是上年最后一周
      weekDays = 7 * (weeknum - 1) + (7 - newYearWeek + 1);
    }
    var startmonth;
    for (var i = 0; i < monthDays.length; i++) {
      startmonth = i;
      if (weekDays > monthDays[i]) {
        weekDays -= monthDays[i];
        if (i == monthDays.length - 1) {
          year++;
          startmonth = 0;
        }
      } else {
        break;
      }
    }
    return [year, startmonth, weekDays];
  }
  //传入日期为当年第几周
  function getweeknum(year, month, day) {
    //获取月份天数数组
    var m_days = [
      31,
      28 + is_leap(year),
      31,
      30,
      31,
      30,
      31,
      31,
      30,
      31,
      30,
      31
    ];
    var newtonowday = 0;
    for (var i = 0; i < month; i++) {
      newtonowday += m_days[i];
    }
    newtonowday += day;
    //获取当年第一天是周几
    var newyear_week = new Date(year, 0, 1).getDay();
    var fdaynothisy = false;
    //新年到周第一天的总天数
    if (newyear_week < 5) {
      //新年第一天算年内第一周[周四在本年]
      newtonowday += newyear_week;
      if (newyear_week == 0 && m_days[2] == 29) {
        fdaynothisy = true;
      }
    } else {
      //新年第一天是上年最后一周
      fdaynothisy = true;
      newtonowday -= 7 - newyear_week;
    }
    var weeknum_result = Math.ceil(newtonowday / 7);
    var weekyear = year;
    if (weeknum_result == 0) {
      var beforeyear_fweek = new Date(weekyear - 1, 0, 1).getDay();
      if (beforeyear_fweek < 5 && beforeyear_fweek > 1 && fdaynothisy) {
        weeknum_result = 53;
      } else {
        weeknum_result = 52;
      }
      weekyear--;
    } else if (weeknum_result > 52) {
      var year_lweek = new Date(year, 11, 31).getDay();
      if (year_lweek > 3 && newyear_week < 5) {
        weeknum_result = 53;
      } else {
        weekyear++;
        weeknum_result = 1;
      }
    }
    return [weekyear, weeknum_result];
  }
  //获取今天
  function todaydate(date) {
    var arr = [parseInt(date.split("-")[0]), parseInt(date.split("-")[1]) - 1, parseInt(date.split("-")[2])];
    var nstr = new Date(arr[0], arr[1], arr[2]);
    var ynow = nstr.getFullYear();
    var mnow = nstr.getMonth();
    var dnow = nstr.getDate();
    return [ynow, mnow, dnow];
  }
  // 获取本周
  function thisweek(date) {
    var todayarr = todaydate(date);
    var weekdata = getweeknum(todayarr[0], todayarr[1], todayarr[2]);
    return weekdata;
  }
})(Zepto, window, document);